import { createStorage as create } from './storageCache.js';

const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 1 // 系统默认缓存时间，单位秒

const createOptions = (storage, options) => {
  return {
    hasStruct: true,
    hasEncrypt: false,
    storage,
    prefixKey: 'FOK_',
    ...options,
  }
}

const createStorage = (storage, options) => {
  return create(createOptions(storage, options))
}

const createSessionStorage = (options) => {
  return createStorage('sessionStorage', { ...options, DEFAULT_CACHE_TIME })
}

const createLocalStorage = (options) => {
  return createStorage('localStorage', { ...options, DEFAULT_CACHE_TIME })
}

/**
 * 根据 key 获得 Local 对应的值
 * @param {string} key 
 * @param {boolean} options.hasStruct 是否结构化
 * @param {boolean} options.hasEncrypt 是否加密
 * @param {string} options.prefixKey 前缀
 * @returns {any}
 */
const getLocal = (key, options = {}) => {
  const ls = createLocalStorage(options)
  return ls.get(key)
}

/**
 * 根据 key 设置 Local 对应的值
 * @param {string} key 
 * @param {string|number|object|array} value 
 * @param {boolean} options.hasStruct 是否结构化
 * @param {boolean} options.hasEncrypt 是否加密
 * @param {string} options.prefixKey 前缀
 * @param {object} options
 */
const setLocal = (key, value, options = {}) => {
  const ls = createLocalStorage(options)
  ls.set(key, value)
}

/**
 * 根据 key 删除 Local 对应的值
 * @param {string} key 
 */
const removeLocal = (key) => {
  const ls = createLocalStorage({})
  ls.remove(key)
}

/**
 * 删除全部 Local 对应的值
 */
const clearLocal = () => {
  const ls = createLocalStorage({})
  ls.clear()
}

/**
 * 根据 key 获得 Session 对应的值
 * @param {string} key 
 * @param {object} options
 */
const getSession = (key, options = {}) => {
  const ss = createSessionStorage(options)
  return ss.get(key)
}

/**
 * 根据 key 设置 Session 对应的值
 * @param {string} key 
 * @param {string|number|object|array} value 
 * @param {object} options
 */
const setSession = (key, value, options = {}) => {
  const ss = createSessionStorage(options)
  ss.set(key, value)
}

/**
 * 根据 key 删除 Session 对应的值
 * @param {string} key 
 */
const removeSession = (key) => {
  const ss = createSessionStorage({})
  ss.remove(key)
}

/**
 * 删除全部 Session 对应的值
 */
const clearSession = () => {
  const ss = createSessionStorage({})
  ss.clear()
}

/**
 * 删除全部 Local 与 Session 对应的值
 */
const clearAll = () => {
  const ls = createLocalStorage({})
  const ss = createSessionStorage({})
  ls.clear()
  ss.clear()
}

const Storage = {
  getLocal,
  setLocal,
  removeLocal,
  clearLocal,
  getSession,
  setSession,
  removeSession,
  clearSession,
  clearAll,
}

export { 
  Storage
}